from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.http import require_GET

from app.util.wechat import get_code_address, get_user_info
from app.models.user import User
from app.models.ucode import Ucodes
import random
import string

# 记录前台访问时间
from app.models.index import Index

# cookie加密常量
salts = '45)ux*67c(epdi%mvtqi8o1a3mn(=38@##rfp3voqwtyssf'


# 请勿修改
# 此方法只适用于微信对服务器进行认证不进行其他操作
@require_GET
def check_signature(request):
    """
    微信服务器验证请求
    :param request: 服务器验证请求
    :return: 响应验证
    """
    # 加密签名
    signature = request.GET.get("signature", "")
    # 时间戳
    timestamp = request.GET.get("timestamp", "")
    # 随机数
    nonce = request.GET.get("nonce", "")
    # 随机字符串
    echostr = request.GET.get("echostr", "")
    # 此时暂时忽略对签名进行校验，直接返回
    print("微信正在验证服务器...")
    print("收到参数signature：" + signature)
    print("收到参数timestamp：" + timestamp)
    print("收到参数nonce：" + nonce)
    print("收到参数echostr：" + echostr)
    return HttpResponse(echostr)


# 请勿修改
# 此方法只辅助微信验证回调授权文件
def authorization_file(request):
    """
    处理回调授权文件验证
    :param request: 文件验证请求
    :return: 转向静态资源授权文件目录
    """
    return HttpResponseRedirect("/static/authorization-file/MP_verify_FbsyV1w5OlIBD32g.txt")


def login(request):
    """
    处理用户登陆请求
    此方法应检查cookie中是否存在用户信息，当存在时，直接使用cookie信息，并重定向去登陆首页
    当用户信息不存在时需重定向去微信授权地址获取用户信息
    :param request: 处理用户登陆请求
    :return: 首页，get_code_address
    """
    state = request.GET.get("state", "")
    # 判断本地cookie中用户信息是否存在
    if 'cookie_openid' in request.COOKIES:
        openid = request.get_signed_cookie('cookie_openid', salt=salts)
        uid = request.get_signed_cookie('cookie_uid', salt=salts)
        try:
            user = User.objects.get(wechat_number=openid)
            # 生成32位随机码

            def Makepass(length=32, chars=string.ascii_letters + string.digits):
                return ''.join([random.choice(chars) for i in range(length)])
            ucode = Makepass()
            # 存储code和两个id值
            codes = Ucodes(u_code=ucode, oid=openid, uid=uid)
            codes.save()
            return HttpResponseRedirect("/login/index?state=" + state+"&ucode="+ucode)
        except User.DoesNotExist:
            pass
    return HttpResponseRedirect(get_code_address(state))


def accredit(request):
    """
    向微信请求Code授权后的回调方法
    此方法使用在未发现cookie中的用户信息时，发起微信授权的回调方法
    主要为接收回调，解析code，并设置用户信息到session以及cookie
    :param request: 微信的回调请求
    :return: 暂不处理
    """
    # 身份授权CODE
    code = request.GET.get("code", "")
    # 原始state
    state = request.GET.get("state", "")
    # 获取用户信息字典
    user_info_dict = get_user_info(code)

    """
    {
        'refresh_token': '13_5W6rMXuDmjsESRlFRq8nHzGeJQRtvFhancCEfP8JpWhhCgjvyPpCYPkk3B3SrHSeU5tVGuaq0jNgjSP4pFcv036pLkLansf9sQas1kDcTak',
        'expires_in': 7200,
        'access_token': '13_abIijCEzAFu1AtogfKKzSykb9nQT_WVr5-Tdu2aQ5lrNFhbsrfh4fxmfcvltJhQkh9YJh0WU6BKTGSbPPbLGpCd4oeZKY75eoGGpqPwMbjM',
        'openid': 'oZNGL1VsTfi_-OHu6dtCIBBgr8po',
        'scope': 'snsapi_base'
    }
    """
    # 此处应使用openid换取用户信息
    # 获取openid
    openid = user_info_dict['openid']
    user = None
    try:
        user = User.objects.get(wechat_number=openid)
    except User.DoesNotExist:
        user = User(wechat_number=openid)
        user.save()
    uid = str(user.id)
    # 生成32位随机码

    def Makepass(length=32, chars=string.ascii_letters + string.digits):
            return ''.join([random.choice(chars) for i in range(length)])
    ucode = Makepass()
    # 存储code和两个id值
    codes = Ucodes(u_code=ucode, oid=openid, uid=uid)
    codes.save()
    res = HttpResponseRedirect("/login/index?state=" + state+"&ucode="+ucode)
    # 设置用户信息到cookie
    res.set_signed_cookie('cookie_openid', openid, salt=salts, max_age=86400)
    res.set_signed_cookie('cookie_uid', uid, salt=salts, max_age=86400)
    return res


def index(request):
    """
    此处应放置首页部分
    :param request: 首页预打开请求
    :return: 暂直接输出问候信息
    """
    state = request.GET.get("state", "")
    ucode = request.GET.get("ucode", "")
    if state is not None and state != "":

        # 记录访问时间
        index_data = Index()
        index_data.save()

        if state == 'myorder':
            return HttpResponseRedirect('http://tanqin520.udutech.com:8288?ucode=' + ucode)
        if state == 'menulist':
            return HttpResponseRedirect('http://tanqin520.udutech.com:8100?ucode=' + ucode)
        if state == 'news':
            return HttpResponseRedirect('http://tanqin520.udutech.com:8100?ucode=' + ucode)
    else:
        pass
